package variable
/**
 * 闭包
 * 闭包一定有返回值
 */
 def clouser={
    String name,int age -> println "Hello ${name},My age is ${age}"
 }
//clouser('Groovy',10)
//clouser.call()
//clouser()

def clouser2={println "Hello ${it}"}
//clouser2('Groovy')

def clouser3={String name -> return "Hello ${name}"}
def result=clouser3('Groovy');
//println result


int x=cal(6)
//println x
//用来制定number的阶乘
int fab(int number){
    int result=1
    1.upto(number,{
        num->result*=num
    })
    return result
}

int fab2(int number){
    int result=1
    number.downto(1){
        num-> result*=num
    }
    return result
}
//相加
int cal(int number){
    int result=0
    number.times {num-> result+=num}
    return  result
}

/**
 * 字符串与闭包的结合使用
 */
String str='the 2 and 3 is 5'
//each的遍历
//println str.each {
//如果没有操作，输出为strs本身
//    String temp -> print temp.multiply(2)
//}

//find来查找符合条件的第一个
//println str.find {
//    String s-> s.isNumber()
//}
//println str.findAll{String s-> s.isNumber()}
//
//println str.any {String s-> s.isNumber()}
//
//println str.every {
//    String s->s.isNumber()
//}
//
//println str.collect {it.toUpperCase()}

/**
 * 闭包进阶
 * 闭包中的三个变量：this，owner,delegate
 */
def scriptClouser={
    println "scriptClouser this:"+this //代表闭包定义处的类
    println "scriptClouser owner:"+owner //代表闭包定义处的类或对象
    println "scriptClouser delegate:"+delegate //任意一个第三方对象，默认与owner一致
}
//scriptClouser.call()

//内部类
class Person{
    def static classClouser={
        println "classClouser this:"+this
        println "classClouser owner:"+owner
        println "classClouser delegate:"+delegate
    }

    def static say(){
        def  classClouser={
            println "classClouser this:"+this
            println "classClouser owner:"+owner
            println "classClouser delegate:"+delegate
        }
        classClouser.call()
    }
}
//Person.classClouser.call()
//Person.say()
Person p=new Person();
//闭包中
def nestClouser={
    def innerClouser={
        println "innerClouser this:"+this
        println "innerClouser owner:"+owner
        println "innerClouser delegate:"+delegate
    }
    innerClouser.delegate=p
    innerClouser.call()
}
//nestClouser.call()
/**
 * 闭包的委托策略
 */
class Student{
    String name
    def pretty={"My name is ${name}"}
    String toString(){
        pretty.call()
    }

}
class Teacher{
    String name
}
 def stu=new Student(name: 'Sarash')
def tea=new Teacher(name: 'Onderoid')

stu.pretty.delegate=tea
stu.pretty.resolveStrategy=Closure.DELEGATE_FIRST
println stu.toString()

